package com.itdaqi.gulimall.product.exception;

import com.itdaqi.common.exception.BizCodeEnume;
import com.itdaqi.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Daqi
 * @Date 2020/12/17 11:08
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice("com.itdaqi.gulimall.product.controller")
public class gulimallExceptionControllerAdvice {
    /**
     * 进行错误信息验证
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){

        log.error("数据校验出现错误：{},类型错误：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach((fieldError)->{
            //.getField()校验错误的字段。   .getDefaultMessage()校验错误的提示信息
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("error",map);
    }
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        log.error("数据校验出现错误：{},类型错误：{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
